package com.zyf.concurrency.chapter14;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.AttributesExImpl;
import com.zyf.concurrency.annotations.GuardedBy;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用显式条件变量的有界缓存
 * 引自原文：
 *      程序清单14-11给出了有界缓存的另一种实现，即使用两个Condition,分别为notFull和
 * notEmpty，用于表示“非满”与“非空”两个条件谓词。当缓存为空时，take 将阻塞并等待
 * notEmpty，此时put向notEmpty发送信号，可以解除任何在take中阻塞的线程。
 * create by yifeng
 */
public class ConditionBoundedBuffer <T> {
    protected final Lock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();
    private static final int BUFFER_SIZE = 100;
    @GuardedBy("lock") private final T[] items = (T[]) new Object[BUFFER_SIZE];
    @GuardedBy("lock") private int tail, head, count;

    // 阻塞并直到：notFull
    public void put(T x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length)
                notFull.await();
            items[tail] = x;
            if (++tail == items.length)
                tail = 0;
            ++count;
            // 发送通知，相当于notify、notifyAll
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    // 阻塞并直到：notEmpty
    public T take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0)
                notEmpty.await();
            T x = items[head];
            items[head] = null;
            if (++head == items.length)
                head = 0;
            --count;
            // 发送通知，相当于notify、notifyAll
            notFull.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }

}
